using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace IcsSEMCtrl.Util
{
	public class GlobalKeyboardHook
	{
		public delegate int keyboardHookProc(int code, int wParam, ref GlobalKeyboardHook.keyboardHookStruct lParam);
		public struct keyboardHookStruct
		{
			public int vkCode;
			public int scanCode;
			public int flags;
			public int time;
			public int dwExtraInfo;
		}
		private const int VK_SHIFT = 16;
		private const int VK_CONTROL = 17;
		private const int VK_MENU = 18;
		private const int WH_KEYBOARD_LL = 13;
		private const int WM_KEYDOWN = 256;
		private const int WM_KEYUP = 257;
		private const int WM_SYSKEYDOWN = 260;
		private const int WM_SYSKEYUP = 261;
		public List<Keys> HookedKeys = new List<Keys>();
		private IntPtr hhook = IntPtr.Zero;
		private GlobalKeyboardHook.keyboardHookProc khp;
		public event KeyEventHandler KeyDown;
		public event KeyEventHandler KeyUp;
		public GlobalKeyboardHook()
		{
			this.khp = new GlobalKeyboardHook.keyboardHookProc(this.hookProc);
			this.hook();
		}
		~GlobalKeyboardHook()
		{
			this.unhook();
		}
		public void hook()
		{
			IntPtr hInstance = GlobalKeyboardHook.LoadLibrary("User32");
			this.hhook = GlobalKeyboardHook.SetWindowsHookEx(13, this.khp, hInstance, 0u);
		}
		public void unhook()
		{
			GlobalKeyboardHook.UnhookWindowsHookEx(this.hhook);
		}
		public int hookProc(int code, int wParam, ref GlobalKeyboardHook.keyboardHookStruct lParam)
		{
			int result;
			if (code >= 0)
			{
				Keys keys = (Keys)lParam.vkCode;
				if ((GlobalKeyboardHook.GetKeyState(17) & 128) != 0)
				{
					keys |= Keys.Control;
				}
				if ((GlobalKeyboardHook.GetKeyState(18) & 128) != 0)
				{
					keys |= Keys.Alt;
				}
				if ((GlobalKeyboardHook.GetKeyState(16) & 128) != 0)
				{
					keys |= Keys.Shift;
				}
				KeyEventArgs keyEventArgs = new KeyEventArgs(keys);
				if ((wParam == 256 || wParam == 260) && this.KeyDown != null)
				{
					this.KeyDown(this, keyEventArgs);
				}
				else
				{
					if ((wParam == 257 || wParam == 261) && this.KeyUp != null)
					{
						this.KeyUp(this, keyEventArgs);
					}
				}
				if (keyEventArgs.Handled)
				{
					result = 1;
					return result;
				}
			}
			result = GlobalKeyboardHook.CallNextHookEx(this.hhook, code, wParam, ref lParam);
			return result;
		}
		[DllImport("user32.dll")]
		private static extern IntPtr SetWindowsHookEx(int idHook, GlobalKeyboardHook.keyboardHookProc callback, IntPtr hInstance, uint threadId);
		[DllImport("user32.dll")]
		private static extern bool UnhookWindowsHookEx(IntPtr hInstance);
		[DllImport("user32.dll")]
		private static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref GlobalKeyboardHook.keyboardHookStruct lParam);
		[DllImport("kernel32.dll")]
		private static extern IntPtr LoadLibrary(string lpFileName);
		[DllImport("user32.dll")]
		private static extern short GetKeyState(int nCode);
	}
}
